package com.app.mingluxing.chat;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.app.mingluxing.R;
import com.app.mingluxing.base.BaseActivity;
import com.app.mingluxing.bean.AddressBean;
import com.app.mingluxing.bean.MessageBean;
import com.app.mingluxing.net.HttpUtil;
import com.app.mingluxing.sort.CharacterParser;
import com.app.mingluxing.sort.PinyinComparator;
import com.app.mingluxing.sort.SideBarView;
import com.app.mingluxing.sort.SortAdapter;
import com.app.mingluxing.sort.SortModel;
import com.app.mingluxing.utils.Constant;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import de.greenrobot.event.EventBus;

/**
 * 好友列表页面
 * Created by Aaron on 16/1/19.
 */
public class ContractsActivity extends BaseActivity {

    private ListView lvcontract;
    private ImageView iv_left;
    private List<AddressBean.ContactsEntity> contacts;
    private Intent mIntent;
    private List<SortModel> sortList = new ArrayList<>();

    /**
     * 汉字转换拼音的类
     */
    private CharacterParser characterParser;
    //    private List<SortModel> SourceDateList;
    //根据拼音来排列ListView里面的数据类
    private PinyinComparator pinyinComparator;
    private SideBarView sidrbar;
    private SortAdapter adapter;
    private SortModel currentSortModel;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_friend_list);

        initWidget();

        //实例化汉字转拼音类
        characterParser = CharacterParser.getInstance();

        pinyinComparator = new PinyinComparator();

        adapter = new SortAdapter(this, sortList);

        EventBus.getDefault().register(this);

    }

    @Override
    protected void onResume() {
        super.onResume();

        getFriendList();
    }

    /**
     * 删除了好友
     *
     * @param msb
     */
    public void onEventMainThread(MessageBean msb) {

        switch (msb.operationStyle) {

            case Constant.OFF_GROUP:

                if (sortList == null || adapter == null)
                    return;

                sortList.remove(currentSortModel);
                adapter.notifyDataSetChanged();
                break;

        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        EventBus.getDefault().unregister(this);
    }

    private void initWidget() {

        iv_left = (ImageView) findViewById(R.id.iv_left);
        this.lvcontract = (ListView) findViewById(R.id.lv_contract);
        LinearLayout ll_group = (LinearLayout) findViewById(R.id.ll_group);
        LinearLayout ll_new_friends = (LinearLayout) findViewById(R.id.ll_new_friends);
        LinearLayout ll_family_group = (LinearLayout) findViewById(R.id.ll_family_group);

        TextView tv_right = (TextView) findViewById(R.id.tv_right);

        tv_right.setText(getResources().getString(R.string.refresh));

        ((TextView) findViewById(R.id.tv_title)).setText(getResources().getString(R.string.contract));

        sidrbar = (SideBarView) findViewById(R.id.sidrbar);

        //设置右侧触摸监听
        sidrbar.setOnTouchingLetterChangedListener(new SideBarView.OnTouchingLetterChangedListener() {

            @Override
            public void onTouchingLetterChanged(String s) {
                //该字母首次出现的位置
                int position = adapter.getPositionForSection(s.charAt(0));
                if (position != -1) {
                    lvcontract.setSelection(position);

                }

            }
        });

        iv_left.setOnClickListener(this);
        ll_group.setOnClickListener(this);
        ll_new_friends.setOnClickListener(this);
        tv_right.setOnClickListener(this);
        ll_family_group.setOnClickListener(this);

        lvcontract.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                if (contacts == null)
                    return;

                currentSortModel = sortList.get(position);

                mIntent = new Intent(ContractsActivity.this, ContractDetailActivity.class);
                mIntent.putExtra("contact", sortList.get(position));
                startActivity(mIntent);

            }
        });

    }

    /**
     * 获取通讯录
     */
    private void getFriendList() {

        JSONObject j = new JSONObject();

        j.put("token", sp.getString(Constant.TOKEN, ""));

        HttpUtil.setPostRequest("获取中...", this, Constant.WEB_ROOT_TALK + Constant.MYCONTACTS,
                j.toString(), getClass().getName(), new HttpUtil.SuccessListener() {
                    @Override
                    public void setOnSuccessListener(String str) {

                        try {

                            AddressBean ab = JSONObject.parseObject(str, AddressBean.class);

                            if (ab.code == Constant.STATUS_SUCCESS) {

                                handleResult(ab.contacts);

                            } else {
                                showToast(Constant.showErrorMsg(ab.code, ContractsActivity.this));
                            }

                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                    }
                }, null);

    }

    /**
     * 处理数据
     *
     * @param contacts
     */
    private void handleResult(List<AddressBean.ContactsEntity> contacts) {

        this.contacts = contacts;

        SortModel sortModel;

        if (sortList != null)
            sortList.clear();

        for (int i = 0; i < contacts.size(); i++) {

            sortModel = new SortModel();

            sortModel.name = contacts.get(i).user.nickName;
            sortModel.url = contacts.get(i).user.imgUrl;
            sortModel.phone = contacts.get(i).user.phoneNum;
            sortModel.topic = contacts.get(i).topic;

            String pinyin = characterParser.getSelling(sortModel.name);
            String sortString = pinyin.substring(0, 1).toUpperCase();

            // 正则表达式 判断首字母是否是英文字母
            if (sortString.matches("[A-Z]")) {
                sortModel.sortLetters = sortString.toUpperCase();
            } else {
                sortModel.sortLetters = "#";
            }

            sortList.add(sortModel);
        }

//        LogUtil.e("tag", "sortList 的个数 : " + sortList.size());

        // 根据a-z进行排序源数据
        Collections.sort(sortList, pinyinComparator);
//        AddressAdapter adapter = new AddressAdapter(this, contacts);
        lvcontract.setAdapter(adapter);
    }

    @Override
    public void widgetClick(View v) {

        switch (v.getId()) {

            case R.id.iv_left:
                finish();
                break;

            case R.id.ll_group://群列表

                mIntent = new Intent(this, ChatGroupListActivity.class);
                startActivity(mIntent);

                break;

            case R.id.ll_new_friends://新的好友

                mIntent = new Intent(this, NewFriendsActivity.class);
                startActivity(mIntent);

                break;

            case R.id.ll_family_group://家庭圈

                mIntent = new Intent(this, FamilyGroupActivity.class);
                startActivity(mIntent);

                break;

            case R.id.tv_right:

                getFriendList();

                break;

        }

    }


}
